import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Register from '@/views/register'
import Layout from '@/views/layout'
import Collect from '@/views/collect'
import MyRent from '@/views/myrent'
import CityList from '@/views/citylist'
import Publish from '@/views/publish'
// 二级路由
import FindHouse from '@/views/findhouse'
import Information from '@/views/information'
import MainPage from '@/views/mainpage'
import Users from '@/views/users'
import User from '@/views/user'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/collect', component: Collect },
    { path: '/myrent', component: MyRent },
    { path: '/citylist', component: CityList },
    { path: '/publish', component: Publish },
    {
      path: '/',
      component: Layout,
      redirect: '/mainpage',
      children: [
        { path: '/mainpage', component: MainPage },
        { path: '/findhouse', component: FindHouse },
        { path: '/information', component: Information },
        { path: '/users', component: Users },
        { path: '/user', component: User }
      ]
    }
  ]
})

// 全局前置守卫:
// 1. 所有的路由一旦被匹配到，在真正渲染解析之前，都会先经过全局前置守卫
// 2. 只有全局前置守卫放行，才能看到真正的页面
// 白名单
// to: 去哪个页面  from: 从哪个页面过来  next: 是否放行
const whiteList = ['/register', '/login', '/user']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next() // 如果有token 直接放行
  } else {
    // 判断是否在白名单
    if (whiteList.includes(to.path)) {
      next() // 如果在白名单 就放行
    } else {
      next('/login') // 如果不在白名单，就跳到登录页面
    }
  }
})

export default router
